Ext.define('App.reportconfiguration.chartconfiguration.field.SeriesGridField', {
    extend: 'Extend.form.field.GridField',
    alias: ['widget.SeriesGridField'],
    controller: 'SeriesGridFieldController',
    border: false,
    roweditable: true,
    sortableColumns: false,
    submitFields: ['id', 'type', 'xField', 'yFields', 'axis', 'percent', 'stacked', 'fill', {column: 'index', field: 'idx'}],
    listeners: {
        beforeedit: 'onBeforeEdit'
    },
    columns: [{
        text: 'ID',
        dataIndex: 'id',
        hidden: true
    }, {
        text: '类型',
        dataIndex: 'type',
        flex: 1,
        menuDisabled: true,
        renderer: function (v, m, r) {
            switch (v) {
                case 'line':
                    return '折线';
                    break;
                case 'bar':
                    return '柱状';
                    break;
                case 'bar3d':
                    return '柱状3D';
                    break;
                case 'pie':
                    return '饼图';
                    break;
                case 'pie3d':
                    return '饼图3D';
                    break;
                case 'area':
                    return '区域';
                    break;
                case 'scatter':
                    return '散点';
                    break;
                default:
                    return v;
            }
        },
        editor: {
            xtype: 'SeriesTypeComboBox',
            allowBlank: false,
            listeners: {change: 'onSeriesTypeChange'}
        }
    }, {
        text: 'X轴数据',
        dataIndex: 'xField',
        flex: 1,
        menuDisabled: true,
        editor: {
            xtype: 'XAxisComboBox',
            allowBlank: false
        }
    }, {
        text: 'Y轴',
        dataIndex: 'axis',
        menuDisabled: true,
        flex: 1,
        editor: {
            xtype: 'AxisDirectionComboBox',
            allowBlank: false,
            listeners: {
                change: 'onAxisDirectionChange'
            }
        }
    }, {
        flex: 3,
        text: 'Y轴数据',
        dataIndex: 'yFields',
        menuDisabled: true,
        editor: {
            xtype: 'YAxisComboBox',
            allowBlank: false,
            itemId: 'yFields'
        }
    }, {
        text: '百分比',
        menuDisabled: true,
        dataIndex: 'percent',
        renderer: function (v, m, r) {
            return (v == true) ? '是' : '否';
        },
        editor: {
            xtype: 'booleancombobox',
            itemId: 'percent',
            allowBlank: false
        }
    }, {
        text: '堆叠',
        menuDisabled: true,
        dataIndex: 'stacked',
        renderer: function (v, m, r) {
            return (v == true) ? '是' : '否';
        },
        editor: {
            xtype: 'booleancombobox',
            itemId: 'stacked',
            readOnly: true,
            allowBlank: false
        }
    }, {
        text: '填充',
        menuDisabled: true,
        dataIndex: 'fill',
        renderer: function (v, m, r) {
            return (v == true) ? '是' : '否';
        },
        editor: {
            xtype: 'booleancombobox',
            itemId: 'fill',
            readOnly: true,
            allowBlank: false
        }
    }],
    checkDatas: function (axisStore) {
        function findRefSource(store, field) {
            var records = store.queryBy(function (record) {
                var axisFields = record.get('fieldsArray');
                var finded = Ext.Array.findBy(axisFields, function (item) {
                    if (item == field) {
                        return true;
                    }
                    return false;
                });
                return !Ext.isEmpty(finded)
            });
            return records;
        }

        var store = this.getStore();
        store.each(function (record) {
                var yFields = record.get('yFieldsArray');
                for (var i = yFields.length - 1; i >= 0; i--) {
                    var field = yFields[i];
                    var records = findRefSource(axisStore, field);
                    if (records.getCount() > 0) {
                        records.each(function (item) {
                            record.set('axis', item.get('title'))
                        })
                    } else {
                        Ext.Array.remove(yFields, field);
                    }
                }
                record.set("yFields", yFields);
            }
        )
    }
})


Ext.define('App.reportconfiguration.chartconfiguration.field.SeriesGridFieldController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.SeriesGridFieldController',
    onSeriesTypeChange: function (combobox, nv, ov) {
        var me = this;
        var stackedCombobox = combobox.up().down('booleancombobox[itemId="stacked"]');
        if (!Ext.isEmpty(stackedCombobox)) {
            if (nv == 'bar' || nv == 'bar3d' || nv == 'area') {
                stackedCombobox.setReadOnly(false);
            } else {
                stackedCombobox.setReadOnly(true);
                stackedCombobox.setValue(false)
            }
        }
        var fillCombobox = combobox.up().down('booleancombobox[itemId="fill"]');
        if (!Ext.isEmpty(fillCombobox)) {
            if (nv == 'line') {
                fillCombobox.setReadOnly(false);
            } else {
                fillCombobox.setReadOnly(true);
                fillCombobox.setValue(false)
            }
        }

        var AxisDirectionComboBox = combobox.up().down('AxisDirectionComboBox');
        this.createYFieldCombobox(nv);
        if (nv == 'pie' || nv == 'pie3d') {
            combobox.up().down('AxisDirectionComboBox').disable();
            combobox.up().down('combobox[itemId="yFields"]').disable();
        } else {
            combobox.up().down('AxisDirectionComboBox').enable();
            combobox.up().down('combobox[itemId="yFields"]').enable();
        }
        AxisDirectionComboBox.fireEvent('change', AxisDirectionComboBox, AxisDirectionComboBox.getValue());
    },
    createYFieldCombobox: function (type) {
        var rowedit = this.getView().findPlugin('extendrowediting');
        var columns = rowedit.grid.columns;
        var editor = columns[4].getEditor();
        var width = null;
        var value = editor.getValue();
        try {
            width = editor.getWidth();
        } catch (e) {
            width = columns[4].getWidth();
        }
        if (!Ext.isEmpty(editor)) {
            columns[4].setEditor();
            editor = null;
        }
        if (Ext.String.startsWith(type, 'bar') || Ext.String.startsWith(type, 'bar3d') || Ext.String.startsWith(type, 'area')) {
            editor = Ext.create({
                xtype: 'YAxisComboBox',
                itemId: 'yFields',
                width: width
            });
        } else {
            editor = Ext.create({
                xtype: 'combobox',
                allowBlank: false,
                valueField: 'name',
                displayField: 'name',
                editable: false,
                queryMode: 'local',
                itemId: 'yFields',
                width: width,
                store: Ext.create('Ext.data.Store', {
                    fields: ['name', 'value'],
                    data: []
                })
            });
        }
        columns[4].setEditor(editor);
    },
    onAxisDirectionChange: function (combobox, nv, ov) {
        var me = this;
        var YAxisComboBox = combobox.up().down('combobox[itemId="yFields"]');
        var updateYAxisComboBox = function () {
            var datas = [];

            var record = me.getView().up().down('AxisGridField').getStore().findRecord('title', nv);
            if (!Ext.isEmpty(record)) {
                var fields = record.get('fields').split(',');
                for (var i = 0; i < fields.length; i++) {
                    datas.push({name: fields[i].trim(), value: fields[i].trim()});
                }
            }
            YAxisComboBox.getStore().setData(datas);
        }
        if (!Ext.isEmpty(nv)) {
            updateYAxisComboBox();
        } else {
            YAxisComboBox.getStore().setData([]);
        }
    },
    onBeforeEdit: function (roweditor, e, eOpts) {
        var me = this;
        var updateSeriesTypeComboBox = function () {
            var isStereoscopic = me.getView().up('ChartConfigurationEditor').down('checkbox[name="stereoscopic"]').getValue();
            var isPie = me.getView().up('ChartConfigurationEditor').down('checkbox[name="pie"]').getValue();
            var SeriesTypeComboBox = roweditor.editor.down('SeriesTypeComboBox');
            var SeriesTypeComboBoxStore = SeriesTypeComboBox.getStore();
            if (isStereoscopic == true) {
                if (isPie == true) {
                    SeriesTypeComboBoxStore.setData([{value: 'pie3d', name: "饼图3D"}]);
                } else {
                    SeriesTypeComboBoxStore.setData([{value: 'bar3d', name: "柱状3D"}]);
                }
            } else {
                if (isPie == true) {
                    SeriesTypeComboBoxStore.setData([{value: 'pie3d', name: "饼图3D"}, {value: 'pie', name: "饼图"}]);
                } else {
                    SeriesTypeComboBoxStore.setData([{value: 'bar', name: "柱状"}, {value: 'line', name: "折线"}, {value: 'area', name: "区域"}, {value: 'scatter', name: "散点图"}]);
                }
            }
            SeriesTypeComboBox.fireEvent('change', SeriesTypeComboBox, e.record.get('type'))
        }
        var updateAxisDirectionComboBox = function () {
            var AxisDirectionComboBox = roweditor.editor.down('AxisDirectionComboBox');
            var AxisGridField = me.getView().up('ChartConfigurationEditor').down('AxisGridField');
            var datas = [];
            AxisGridField.getStore().each(function (record) {
                if (Ext.String.startsWith(record.get('type'), 'numeric')) {
                    datas.push({title: record.get('title'), position: record.get('position')});
                }
            });
            AxisDirectionComboBox.getStore().setData(datas);
            AxisDirectionComboBox.fireEvent('change', AxisDirectionComboBox, e.record.get('axis'))
        }
        var updateXAxisComboBox = function () {
            var AxisGridField = me.getView().up('ChartConfigurationEditor').down('AxisGridField');
            var XAxisComboBox = roweditor.editor.down('XAxisComboBox');
            var isPie = me.getView().up('ChartConfigurationEditor').down('checkbox[name="pie"]').getValue();
            var datas = [];
            AxisGridField.getStore().each(function (record) {
                if (isPie == true) {
                    if (Ext.String.startsWith(record.get('type'), 'numeric')) {
                        var fields = record.get('fields');
                        datas.push({name: fields, value: fields});
                    }
                } else {
                    if (Ext.String.startsWith(record.get('type'), 'category') || Ext.String.startsWith(record.get('type'), 'time')) {
                        var fields = record.get('fields');
                        datas.push({name: fields, value: fields});
                    }
                }
            });
            XAxisComboBox.getStore().setData(datas);
        }
        updateSeriesTypeComboBox();
        updateAxisDirectionComboBox();
        updateXAxisComboBox();
    }
})


Ext.define('App.reportconfiguration.chartconfiguration.field.SeriesTypeComboBox', {
    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.SeriesTypeComboBox',
    editable: false,
    queryMode: 'local',
    valueField: 'value',
    displayField: 'name',
    store: Ext.create('Ext.data.Store', {
        fields: ['value', 'name'],
        data: []
    })
})

Ext.define('App.reportconfiguration.chartconfiguration.field.AxisDirectionComboBox', {
    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.AxisDirectionComboBox',
    editable: false,
    queryMode: 'local',
    valueField: 'title',
    displayField: 'title',
    store: Ext.create('Ext.data.Store', {
        fields: ['title', 'position'],
        data: []
    })
})

Ext.define('App.reportconfiguration.chartconfiguration.field.XAxisComboBox', {
    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.XAxisComboBox',
    editable: false,
    queryMode: 'local',
    valueField: 'name',
    displayField: 'name',
    store: Ext.create('Ext.data.Store', {
        fields: ['name', 'value'],
        data: []
    })
})

Ext.define('App.reportconfiguration.chartconfiguration.field.YAxisComboBox', {
    extend: 'Extend.form.field.CheckCombo',
    alias: 'widget.YAxisComboBox',
    valuesToString: true,
    allowBlank: false,
    valueField: 'name',
    displayField: 'name',
    editable: false,
    queryMode: 'local',
    store: Ext.create('Ext.data.Store', {
        fields: ['name', 'value'],
        data: []
    })
})